//
//  YTPhotoLibraryManager.m
//  YUNT
//
//  Created by haha on 2017/11/19.
//  Copyright © 2017年 梁炜东. All rights reserved.
//

#import "YTPhotoLibraryManager.h"

@implementation YTPhotoLibraryItem

@end

static YTPhotoLibraryManager *manager = nil;

@implementation YTPhotoLibraryManager

- (instancetype)init
{
    self = [super init];
    
    if (self)
    {
        _allImages = [NSDictionary dictionary];
        
        _allVideos = [NSDictionary dictionary];
        
        _allResources = [NSDictionary dictionary];
        
        _allKeys = [NSArray array];
        
        _videoKeys = [NSArray array];
        
        _imageKeys = [NSArray array];
        
        _selectedImages = [NSMutableArray array];
        
        _selectedVideos = [NSMutableArray array];
        
        _selectedResources = [NSMutableArray array];
    }
    return self;
}

+ (YTPhotoLibraryManager *)defaultManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YTPhotoLibraryManager alloc] init];
    });
    return manager;
}

- (void)dealloc
{
    [self clearManager];
}

- (void) clearManager
{
    _allImages = nil;
    
    _allVideos = nil;
    
    _allResources = nil;
    
    _allKeys = nil;
    
    _videoKeys = nil;
    
    _imageKeys = nil;
    
    _selectedImages = nil;
    
    _selectedVideos = nil;
    
    _selectedResources = nil;
}

- (void)readResourcesFromSandbox
{
    [self readAllImages];
    
    [self readAllVideos];
    
    [self readAllResources];
    
    [self sortAllKeys];
}

- (void)readAllImages
{
    NSError *error = nil;
    
    NSArray *photoArray = [FileManager contentsOfDirectoryAtPath:kPhotoPath error:&error];
    
    NSMutableDictionary *imagesDic = [NSMutableDictionary dictionary];
    
    for (NSString *item in photoArray)
    {
        NSString *dataString = [kPhotoPath stringByAppendingString:item];
        
        NSData *data = [NSData dataWithContentsOfFile:dataString];
        
        NSDictionary *fileAttributes = [FileManager attributesOfItemAtPath:dataString error:nil];
        
        YTPhotoLibraryItem *resouceItem = [[YTPhotoLibraryItem alloc] init];
        
        resouceItem.resourceData = data;
        
        resouceItem.resourceName = item;
        
        NSDate *date = fileAttributes[@"NSFileModificationDate"] ? fileAttributes[@"NSFileModificationDate"] : fileAttributes[@"NSFileCreationDate"];
        
        resouceItem.resourceDate = [NSString stringWithFormat:@"%@",date];
        
        resouceItem.resourceIndentifier = [NSString stringWithFormat:@"%@",fileAttributes[@"NSFileSystemFileNumber"]];
        
        NSArray *arr = [item componentsSeparatedByString:@"."];
        
        resouceItem.resourceType = arr.lastObject;
        
        NSString *timeStr = resouceItem.resourceDate;
        
        timeStr = [timeStr componentsSeparatedByString:@" "].firstObject;
        
        if (imagesDic[timeStr])
        {
            [imagesDic[timeStr] addObject:resouceItem];
        }
        else
        {
            NSMutableArray *arr = [NSMutableArray array];
            
            [arr addObject:resouceItem];
            
            [imagesDic setValue:arr forKey:timeStr];
        }
    }
    
    self.allImages = [NSDictionary dictionaryWithDictionary:imagesDic];
}

- (void)readAllVideos
{
    NSError *error = nil;
    
    NSArray *videoArray = [FileManager contentsOfDirectoryAtPath:kVideoPath error:&error];
    
    NSMutableDictionary *videosDic = [NSMutableDictionary dictionary];
    
    for (NSString *item in videoArray)
    {
        NSString *dataString = [kVideoPath stringByAppendingString:item];
        
        NSData *data = [NSData dataWithContentsOfFile:dataString];
        
        NSDictionary *fileAttributes = [FileManager attributesOfItemAtPath:dataString error:nil];
        
        YTPhotoLibraryItem *resouceItem = [[YTPhotoLibraryItem alloc] init];
        
        resouceItem.resourceData = data;
        
        resouceItem.resourceName = item;
        
        NSDate *date = fileAttributes[@"NSFileModificationDate"] ? fileAttributes[@"NSFileModificationDate"] : fileAttributes[@"NSFileCreationDate"];
        
        resouceItem.resourceDate = [NSString stringWithFormat:@"%@",date];
        
        resouceItem.resourceIndentifier = [NSString stringWithFormat:@"%@",fileAttributes[@"NSFileSystemFileNumber"]];
        
        NSArray *arr = [item componentsSeparatedByString:@"."];
        
        resouceItem.resourceType = arr.lastObject;
        
        NSString *timeStr = resouceItem.resourceDate;
        
        timeStr = [timeStr componentsSeparatedByString:@" "].firstObject;
        
        if (videosDic[timeStr])
        {
            [videosDic[timeStr] addObject:resouceItem];
        }
        else
        {
            NSMutableArray *arr = [NSMutableArray array];
            
            [arr addObject:resouceItem];
            
            [videosDic setValue:arr forKey:timeStr];
        }
    }
    
    self.allVideos = [NSDictionary dictionaryWithDictionary:videosDic];
}

- (void)readAllResources
{
    NSMutableSet *allKeys = [NSMutableSet set];
    
    for (NSString *key in self.allImages.allKeys)
    {
        [allKeys addObject:key];
    }
    
    for (NSString *key in self.allVideos.allKeys)
    {
        [allKeys addObject:key];
    }
    
    NSMutableDictionary *allDic = [NSMutableDictionary dictionary];
    
    for (NSString *key in allKeys)
    {
        if (self.allImages[key])
        {
            if (allDic[key])
            {
                [allDic[key] addObjectsFromArray:[NSMutableArray arrayWithArray:self.allImages[key]]];
            }
            else
            {
                [allDic setValue:[NSMutableArray arrayWithArray:self.allImages[key]] forKey:key];
            }
        }
        if (self.allVideos[key])
        {
            if (allDic[key])
            {
                [allDic[key] addObjectsFromArray:self.allVideos[key]];
            }
            else
            {
                [allDic setValue:[NSMutableArray arrayWithArray:self.allVideos[key]] forKey:key];
            }
        }
    }
    
    self.allResources = [NSDictionary dictionaryWithDictionary:allDic];
}

- (void)sortAllKeys
{
    self.allKeys = [self.allResources.allKeys sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
        
        return (NSComparisonResult)[obj2 compare:obj1 options:NSNumericSearch];
    }];
    
    self.videoKeys = [self.allVideos.allKeys sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
        
        return (NSComparisonResult)[obj2 compare:obj1 options:NSNumericSearch];
    }];
    
    self.imageKeys = [self.allImages.allKeys sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
        
        return (NSComparisonResult)[obj2 compare:obj1 options:NSNumericSearch];
    }];
}

- (NSArray *)readAllImagesArray
{
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSString *key in self.imageKeys)
    {
        if (self.allImages[key])
        {
            [array addObjectsFromArray:self.allImages[key]];
        }
    }
    
    return [NSArray arrayWithArray:array];
}

- (void)fetchSandboxResourcesWithCompletion:(nonnull finishFetchSizeBlock)completion
{
    
}

@end
